package com.xy.biz.auth.controller;

import com.wf.captcha.SpecCaptcha;
import com.xy.biz.auth.domain.bo.CaptchaBO;
import com.xy.biz.auth.domain.req.GetCaptchaRequest;
import com.xy.biz.auth.domain.resp.GetCaptchaResponse;
import com.xy.biz.auth.service.CaptchaService;
import com.xy.lang.domain.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/api/auth/captcha")
public class CaptchaController {

    @Autowired
    private CaptchaService captchaService;

    @PostMapping(value = "/get")
    public Result<GetCaptchaResponse> getCaptcha(@RequestBody GetCaptchaRequest request,
                                                 HttpServletRequest servletRequest, HttpServletResponse servletResponse)
            throws Exception {
        //https://github.com/whvcse/EasyCaptcha
        SpecCaptcha specCaptcha = new SpecCaptcha(120, 36, 6);
        String captchaCode = specCaptcha.text().toLowerCase();
        Integer type = request.getType();
        CaptchaBO captchaBO = captchaService.saveCaptcha(captchaCode, (type == null ? 0 : type));
        return Result.success(GetCaptchaResponse.builder()
                .captchaId(captchaBO.getCaptchaId())
                .src(specCaptcha.toBase64())
                .build());
    }

}
